package com.yzl.shiro.demo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

/**
 * 单元侧测试执行用例
 *
 * @BeforeClass->@Before->@Test->@Test->@AfterClass
 */
public class QuickStartTest4_3 {
    private SimpleAccountRealm accountRealm=new SimpleAccountRealm();
    private DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();

    @Before
    public void init() {
        //初始化数据
        accountRealm.addAccount("yaozhili","123","root","admin");
        accountRealm.addAccount("jack","123456","user");
        //构建环境
        defaultSecurityManager.setRealm(accountRealm);
    }

    @Test
    public void testAuthentication() {
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //获取当前的一个主体 application user
        Subject subject=SecurityUtils.getSubject();

        //用户输入的
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("yaozhili","123");
        subject.login(usernamePasswordToken);

        System.out.println("认证结果："+subject.isAuthenticated());
        System.out.println("是否有对应的角色："+subject.hasRole("root"));
        System.out.println("getPrincipal 认证结果："+subject.getPrincipal());
        subject.logout();
        System.out.println("登出后的认证结果："+subject.isAuthenticated());
    }
}
